import HttpRequestService from '../shared/services/http-request-service';
import User from './user';

export default class UserService {
  private static readonly url = '/user';

  /**
   * Retrieves the [User] from backend service with [id].
   */
  static async queryDetails(id: string): Promise<User> {
    const response = await HttpRequestService.get(`${this.url}/queryDetails`, {
      id: id,
    });

    return User.fromJSON(response.payload);
  }

  /**
   * Retrieves current account group users from backend service.
   */
  static async queryAccountGroupUsers(pageSize: number, pageIndex: number): Promise<User[]> {
    // const list: User[] = [];

    // for (let i = pageIndex; i < pageSize * pageIndex + 20; i++) {
    //   list.push({
    //     id: i.toString(),
    //     username: `139 ${i}`,
    //     fullName: `Hui - ${i}`,
    //   });
    // }

    // return list;


    // Gets the response of the http get request.
    // Ant table's pageIndex is 1 based. Server api pageIndex is 0 based. That's why we take [pageIndex - 1].
    const response = await HttpRequestService.get(`${this.url}/queryAccountGroupUsers`, {
      pageSize: pageSize,
      pageIndex: pageIndex - 1,
    });

    // Parses the data from json to [User].
    return response.payload.map((p: any) => User.fromJSON(p));
  }

  /**
   * Adds a new user.
   */
  static async add(user: User): Promise<void> {
    await HttpRequestService.post(`${this.url}/add`, user);
  }

  /**
   * Updates a new user.
   */
  static async update(user: User): Promise<void> {
    await HttpRequestService.post(`${this.url}/update`, user);
  }

  /**
   * Deletes a new user.
   */
  static async delete(ids: string[]): Promise<void> {
    await HttpRequestService.post(`${this.url}/delete`, {
      ids: ids,
    });
  }
}